#include "cliect_td.h"
unsigned long int pid;
unsigned long int id_temp=0;
int sockfd;
Cliect::Cliect()
{
    coorstate=0;
}

Cliect::~Cliect()
{
}

void Cliect::Cliect_RfidId_Process(unsigned int *id)
{
    pid=*(id);
    if(pid!=id_temp)
            {
                id_temp=pid;
                emit Rfid_Changed();
            }
}

void Cliect::run(){
    unsigned int buffer[363]={0};
    while(1)
    {
        unsigned int temp;
        int i=0,count=0;
        tv.tv_sec=2;
        tv.tv_usec=0;
        FD_ZERO(&sds);
        FD_SET(sockfd, &sds);
        int ret = select((1+sockfd), &sds, NULL, NULL, &tv);
        if(ret >0)
        {
            if (FD_ISSET(sockfd, &sds))
            {
                int len=0;
                len=::recv(sockfd,&buffer[i],sizeof(unsigned int),0);
                if(len>0)
                {
                   while(buffer[i]!=0x0A)
                {
                   i++;
                   len=::recv(sockfd,&buffer[i],sizeof(unsigned int),0);
                }
                     if(buffer[0]==0x26)
                {
                    temp=buffer[1];
                    count=i+1;
                    switch(temp)
                    {
                    case 0x04:

                            Cliect_RfidId_Process(&buffer[2]);
                            break;

                    default:
                            printf("error COMMAND\n");
                            break;

                    }
                }
                else
                {
                    printf("other protrol.\n");
                }
            }

            }
            else{
                               printf("not  cliect fd.\n");
                    }
        }
        else if(ret == 0){
            printf("cliect read wait timeout!!!\n");

        }
        else{
            printf("cliect select error.\n");
     
        }
        usleep(30000);

    }

}
void Cliect::GetConnect(char *ipaddr,int port){
    struct sockaddr_in servaddr;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    qDebug("GetConnect sockfd:%d\n",sockfd);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");


    servaddr.sin_port = htons(port);

    if(::connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))!=0){
    perror("Connect ");
    }
}

void Cliect::Api_Cliect_GetRfidId()
{
    unsigned int buffer[3]={0};
    buffer[0]=0x15;
    buffer[1]=0x04;

    buffer[2]='\n';
    int len=::write(sockfd, (unsigned int*)(&buffer), sizeof(buffer));
    if(len<=0)
    {

        qDebug("Api_Cliect_GetRfidId send error\n");
    }
}

